package cn.francis.framework.aspectj;

import cn.francis.common.annoation.Limit;
import cn.francis.common.exception.BusinessException;
import com.google.common.collect.Maps;
import com.google.common.util.concurrent.RateLimiter;
import lombok.extern.slf4j.Slf4j;
import org.aspectj.lang.ProceedingJoinPoint;
import org.aspectj.lang.annotation.Around;
import org.aspectj.lang.annotation.Aspect;
import org.aspectj.lang.reflect.MethodSignature;
import org.springframework.stereotype.Component;

import java.lang.reflect.Method;
import java.util.Map;

/**
 * @author 张俊辉
 */

@Slf4j
@Aspect
@Component
public class LimitAspect {

    private final Map<String, RateLimiter> limiterMap = Maps.newConcurrentMap();

    @Around("@annotation(cn.francis.common.annoation.Limit)")
    public Object around(ProceedingJoinPoint joinPoint) throws Throwable {
        MethodSignature signature = (MethodSignature) joinPoint.getSignature();
        Method method = signature.getMethod();
        Limit annotation = method.getAnnotation(Limit.class);
        if (annotation == null) {
            return joinPoint.proceed();
        }
        String key = annotation.key();
        RateLimiter rateLimiter;
        if (!limiterMap.containsKey(key)) {
            rateLimiter = RateLimiter.create(annotation.permitsPerSecond());
            limiterMap.put(key, rateLimiter);
            log.info("新建了令牌桶={}，容量={}", key, annotation.permitsPerSecond());
        }
        rateLimiter = limiterMap.get(key);
        boolean acquire = rateLimiter.tryAcquire(annotation.timeout(), annotation.timeUnit());
        if (!acquire) {
            log.debug("令牌桶={}，获取令牌失败", key);
            throw new BusinessException(annotation.msg());
        }
        return joinPoint.proceed();
    }
}
